#include<stdio.h>
#include<errno.h>
#include<openssl/ssl.h>
#include<string.h>

/* Macro to turn on compile with POSIX standard IEEE 1003.1-2008 */
#define POSIX_C_SOURCE 200809L

/* Definitions */

#define SLURP_DIGEST_LENGTH 12
#define MAP "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._"

/**
 * Returns 12 byte digest like phabricator
 */
void generate_digest(char *digest, char *hash) {
	for(int i=0;i<SLURP_DIGEST_LENGTH;i++) {
		unsigned int value = hash[i] & 0x3f;
		char c = MAP[value];
		digest[i] = c;
	}
	return;
}





int main(int argc, char **argv) {

	FILE *file = NULL;
	file = fopen("words.txt", "r");

	if(file == NULL) {
		printf("Could not open words.txt\n");
		return 1;
	}

	char *word;
	while(fscanf(file, "%s", word) != EOF) {
	
		if(word == NULL) {
			printf("ERROR: Word is a NULL pointer\n");
			return 1;
		}

		char hash[SHA256_DIGEST_LENGTH];
		size_t length = strlen(word);
		SHA256(word, length, hash);
		
		if(hash != NULL) {
			char *digest = (char*) malloc(SLURP_DIGEST_LENGTH);
			generate_digest(digest, hash);
			printf("%s→%s\n", word, digest);
		} else {
			printf("Hashing failed\n");
		}
	}
	return 0;
}
